package m2;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.List;

/**
 * @author Chenwx
 * @date 2021/5/13 16:26
 */
public class Producer {

        static String[] msgs = {
                "15103111039,创建",
                "15103111065,创建",
                "15103111039,付款",
                "15103117235,创建",
                "15103111065,付款",
                "15103117235,付款",
                "15103111065,完成",
                "15103111039,推送",
                "15103117235,完成",
                "15103111039,完成"
        };

        public static void main(String[] args) throws Exception {
            // 创建生产者
            DefaultMQProducer p = new DefaultMQProducer("producer-group-2");
            // 设置 name server
            p.setNamesrvAddr("192.168.64.141:9876");
            // 启动
            p.start();

            // 发送消息，设置队列选择器
            for (String s : msgs) {
                // 15103117235,付款
                long orderId = Long.parseLong(s.split(",")[0]);

                // 封装消息
                Message msg = new Message("Topic2", s.getBytes());
                // p.send(msg, 队列选择器, 选择依据);
                SendResult r =
                        p.send(msg, new MessageQueueSelector() {
                            @Override
                            public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                                // 收到的三个参数： 服务器端的队列列表, 正要发送的消息, 选择依据
                                Long orderId = (Long) arg;
                                // 用订单id，对队列数量取余
                                int index = (int) (orderId % mqs.size());

                                return mqs.get(index);
                            }
                        }, orderId);

                System.out.println(s+" --> "+r);
            }
        }
    }

